import React, { FC } from "react";
import { GetStaticPaths, GetStaticProps, GetStaticPropsContext } from "next";
import { fetchGuitarDetail, fetchGuitars } from "../../lib/strapi";
import { ParsedUrlQuery } from "querystring";
import { Guitar } from "../../type/guitars";
import Image from "next/image";

const Detail: FC<Props> = ({ guitar }) => {
  return (
    <div>
      <div>ID: {guitar?.id}</div>
      <div>名前：{guitar?.attributes.name}</div>
      <div>説明：{guitar?.attributes.description}</div>
      <div>
        <Image
          src={guitar?.attributes.image.data[0].attributes.url}
          height={240}
          width={560}
        />
      </div>
    </div>
  );
};

interface Props {
  guitar: Guitar;
}

interface IParams extends ParsedUrlQuery {
  id: string;
}

// ===============================
// 静的サイト作成時にはgetStaticPropsの中で
// 表示データを作成する
// ===============================
export const getStaticProps: GetStaticProps = async (ctx) => {
  const { id } = ctx.params as IParams;
  const guitar = await fetchGuitarDetail(id);
  return {
    props: {
      guitar,
    },
  };
};

// ================================
// 表示可能なデータを取得する
// ================================
export const getStaticPaths: GetStaticPaths = async () => {
  const guitars = await fetchGuitars();
  // とりうるIDの一覧を取得する
  const paths = guitars.map((guitars) => ({
    params: {
      id: guitars.id.toString(),
    },
  }));

  return {
    paths,
    fallback: true,
  };
};

export default Detail;
